package com.tencent.welink.util;

import java.security.MessageDigest;

/**
 * @Description: http签名工具栏
 * @Author: limye
 * @CreateDate: 2020-6-8
 * @Version: V1.0
 */
public class HttpSigUtil {

    public static String encrypt(String key, long times, long num) {
        byte[] k = key.getBytes();
        byte[] t = HttpSigUtil.getBytesByLong(times);
        byte[] n = HttpSigUtil.getBytesByLong(num);
        byte[] np = new byte[k.length + t.length + n.length];
        int i = 0;
        for (int j = 0; j < k.length; j++, i++) {
            np[i] = k[j];
        }
        for (int j = 0; j < t.length; j++, i++) {
            np[i] = t[j];
        }
        for (int j = 0; j < n.length; j++, i++) {
            np[i] = n[j];
        }
        String sha1 = HttpSigUtil.getSHA1(np);
        return sha1;
    }

    public static byte[] getBytesByLong(long data) {
        byte[] bytes = new byte[8];
        bytes[0] = (byte) (data & 0xff);
        bytes[1] = (byte) ((data >> 8) & 0xff);
        bytes[2] = (byte) ((data >> 16) & 0xff);
        bytes[3] = (byte) ((data >> 24) & 0xff);
        bytes[4] = (byte) ((data >> 32) & 0xff);
        bytes[5] = (byte) ((data >> 40) & 0xff);
        bytes[6] = (byte) ((data >> 48) & 0xff);
        bytes[7] = (byte) ((data >> 56) & 0xff);
        return bytes;
    }

    public static String getSHA1(byte[] str) {
        String sha1 = "";

        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-1");
            digest.update(str);

            byte messageDigest[] = digest.digest();
            StringBuilder hexString = new StringBuilder();
            for (int i = 0; i < messageDigest.length; i++) {
                String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexString.append(0);
                }
                hexString.append(shaHex);
            }

            sha1 = hexString.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return sha1.toUpperCase();
    }


}
